<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/29
 * Time: 17:46
 */

namespace Common\Model;

class User
{
    protected $tableName = 'users';
    public $id;
    public $email;
    public $password;
    public $age;
    public $sex;
    public $is_baned;
    public $ban_time;
    public $username;

    public function setData($array)
    {
        foreach ($array as $key => $value) {
            $this->$key = $value;
        }
    }

    public function __toString()
    {
        return json_encode($this);
    }

    /**
     * 获取Role
     *
     * @return Role
     */
    public function role()
    {
        $userRole = RoleUsers::findBuUserId($this->id);
        return $userRole->role();
    }

    public static function make(array $data)
    {
        $user = new static();
        $user->setData($data);
        return $user;
    }

    /**
     * @param $id
     * @return null|User
     */
    public static function init($id)
    {
        $user = new static();
        $model = M('users');
        $data = $model->where("id = $id")->find();
        if (empty($data)) {
            return null;
        }
        $user->setData($data);
        return $user;
    }

    /**
     * 更新数据
     *
     * @param array $data
     * @return bool
     */
    public function update(array $data)
    {
        $model = M('users');
        foreach ($data as $key => $value) {
            $model->$key = $value;
        }
        $model->where('id = ' . $this->id)->save();
        return true;
    }
}